package edu.sias.hyzn.service.impl;

import edu.sias.hyzn.mapper.DiseaseStatMapper;
import edu.sias.hyzn.mapper.EyeAnalysisResultMapper;
import edu.sias.hyzn.service.IEyeAnalysisResultService;
import edu.sias.hyzn.vo.DiseaseStatsVO;
import edu.sias.hyzn.vo.DiseaseVO;
import edu.sias.hyzn.vo.EyeAnalysisResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class EyeAnalysisResultService implements IEyeAnalysisResultService {
    private final EyeAnalysisResultMapper eyeAnalysisResultMapper;
    private final DiseaseStatMapper statMapper;

    @Autowired
    public EyeAnalysisResultService(EyeAnalysisResultMapper eyeAnalysisResultMapper, DiseaseStatMapper statMapper) {
        this.eyeAnalysisResultMapper = eyeAnalysisResultMapper;
        this.statMapper = statMapper;
    }
    public List<EyeAnalysisResult> selectEyeAnalysisResultList(EyeAnalysisResult eyeAnalysisResult) {
        return eyeAnalysisResultMapper.selectEyeAnalysisResultList();
    }

    /**
     * 根据分组条件（gender / age / live_city）查询统计结果，
     * 并补齐没有数据的分组值 & 疾病。
     */
    public List<DiseaseStatsVO> getDiseaseStatsByGroup(String groupBy) {
        // 1. 查询数据库中实际有数据的行
        List<DiseaseStatsVO> rawList = statMapper.getDiseaseStatsByGroup(groupBy);

        // 2. 获取所有可能的分组值
        List<String> allGroupValues = getAllGroupValues(groupBy);

        // 3. 获取所有疾病
        List<DiseaseVO> allDiseases = statMapper.getAllDiseases();

        // 4. 为了快速查找，建一个 Map<diseaseCode, DiseaseDTO>
        Map<String, DiseaseVO> diseaseMap = allDiseases.stream()
                .collect(Collectors.toMap(DiseaseVO::getDiseaseCode, d -> d));

        // 5. 将 rawList 转换为 Map<diseaseCode, Map<groupValue, DiseaseStatsVO>>
        Map<String, Map<String, DiseaseStatsVO>> statsMap = new HashMap<>();
        for (DiseaseStatsVO vo : rawList) {
            statsMap
                    .computeIfAbsent(vo.getDiseaseCode(), k -> new HashMap<>())
                    .put(vo.getGroupValue(), vo);
        }

        // 6. 补齐：对每个 disease，再对每个 groupValue 做检查
        List<DiseaseStatsVO> result = new ArrayList<>();
        for (DiseaseVO disease : allDiseases) {
            String diseaseCode = disease.getDiseaseCode();
            // 取到当前 diseaseCode 对应的子 map
            Map<String, DiseaseStatsVO> subMap = statsMap.get(diseaseCode);
            if (subMap == null) {
                subMap = new HashMap<>();
            }
            // 遍历所有分组值
            for (String gv : allGroupValues) {
                DiseaseStatsVO vo = subMap.get(gv);
                if (vo == null) {
                    // 数据库中没有这一行，需要补一个
                    vo = new DiseaseStatsVO();
                    vo.setDiseaseId(disease.getDiseaseId());
                    vo.setDiseaseCode(disease.getDiseaseCode());
                    vo.setDiseaseName(disease.getDiseaseName());
                    vo.setGroupValue(gv);
                    vo.setPatientCount(0);
                }
                result.add(vo);
            }
        }

        // 7. 排序（可选），例如按 diseaseId 升序，再按 groupValue
        // 这里只是示例，可根据实际需求来排
        result.sort(Comparator
                .comparing(DiseaseStatsVO::getDiseaseId)
                .thenComparing(DiseaseStatsVO::getGroupValue));

        return result;
    }

    /**
     * 根据 groupBy 返回所有可能的分组值。
     * gender 固定为 [男, 女, 其他]
     * age 固定为 [Under 18, 18-35, 36-55, 55+]
     * live_city 可能需要动态查询 tb_patient，或有别的获取方式
     */
    private List<String> getAllGroupValues(String groupBy) {
        switch (groupBy) {
            case "gender":
                return Arrays.asList("男", "女", "其他");
            case "age":
                return Arrays.asList("Under 18", "18-35", "36-55", "55+");
            case "live_city":
                // 需要从 tb_patient 中获取所有城市，或写死几个示例
                // return Arrays.asList("北京","上海","广州","深圳");
                // 或者：
                return fetchAllCitiesFromDB();
            default:
                // 如果不支持其他分组，直接返回空
                return Collections.emptyList();
        }
    }

    /**
     * 示例：查询 tb_patient 中所有城市
     * 也可以写在别的 Mapper 里，这里仅做示例
     */
    private List<String> fetchAllCitiesFromDB() {
        // TODO: 这里写查询逻辑
        // 例如 SELECT DISTINCT live_city FROM tb_patient
        return Collections.emptyList();
    }
}
